"""
用户序列化器
处理用户数据的序列化和反序列化
"""

from rest_framework import serializers
from django.contrib.auth import authenticate
from django.contrib.auth.password_validation import validate_password
from .models import User, UserProfile, UserAddress


class UserRegistrationSerializer(serializers.ModelSerializer):
    """
    用户注册序列化器
    """
    
    password = serializers.CharField(
        write_only=True,
        required=True,
        validators=[validate_password],
        style={'input_type': 'password'}
    )
    
    password2 = serializers.CharField(
        write_only=True,
        required=True,
        style={'input_type': 'password'}
    )
    
    class Meta:
        model = User
        fields = [
            'username', 'email', 'password', 'password2',
            'nickname', 'phone', 'gender', 'role'
        ]
        extra_kwargs = {
            'email': {'required': True},
            'nickname': {'required': False},
            'phone': {'required': False},
            'gender': {'required': False},
            'role': {'required': False},
        }
    
    def validate(self, attrs):
        """验证密码一致性"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError("两次输入的密码不一致")
        return attrs
    
    def create(self, validated_data):
        """创建用户"""
        validated_data.pop('password2')
        user = User.objects.create_user(**validated_data)
        
        # 创建用户详细信息
        UserProfile.objects.create(user=user)
        
        return user


class UserLoginSerializer(serializers.Serializer):
    """
    用户登录序列化器
    """
    
    username = serializers.CharField(max_length=255)
    password = serializers.CharField(
        max_length=128,
        write_only=True,
        style={'input_type': 'password'}
    )
    
    def validate(self, attrs):
        """验证用户凭据"""
        import logging
        import traceback
        logger = logging.getLogger('django')
        
        username = attrs.get('username')
        password = attrs.get('password')
        
        logger.debug(f'Login attempt with username: {username}, password length: {len(password) if password else 0}')
        logger.debug(f'Request data keys: {list(attrs.keys())}')
        
        if username and password:
            try:
                logger.debug(f'Attempting to authenticate user: {username}')
                user = authenticate(username=username, password=password)
                logger.debug(f'Authentication result: {user}')
                
                if not user:
                    logger.debug('Authentication failed - invalid credentials')
                    raise serializers.ValidationError('Invalid username or password')
                if not user.is_active:
                    logger.debug(f'Authentication failed - user inactive: {username}')
                    raise serializers.ValidationError('User account is disabled')
                
                attrs['user'] = user
                logger.debug(f'Authentication successful for user: {username}')
                return attrs
            except Exception as e:
                logger.error(f'Authentication error: {str(e)}')
                logger.error(f'Traceback: {traceback.format_exc()}')
                raise serializers.ValidationError(f'Authentication failed: {str(e)}')
        else:
            logger.debug('Authentication failed - missing username or password')
            raise serializers.ValidationError('Username and password are required')


class UserProfileSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """
    
    username = serializers.CharField(source='user.username', read_only=True)
    email = serializers.EmailField(source='user.email', read_only=True)
    nickname = serializers.CharField(source='user.nickname', read_only=True)
    avatar = serializers.ImageField(source='user.avatar', read_only=True)
    
    class Meta:
        model = UserProfile
        fields = [
            'id', 'username', 'email', 'nickname', 'avatar',
            'bio', 'interests', 'credit_score', 'balance',
            'post_count', 'comment_count', 'like_count'
        ]
        read_only_fields = ['credit_score', 'post_count', 'comment_count', 'like_count']


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器（包含所有字段）
    """
    
    profile = UserProfileSerializer(read_only=True)
    
    class Meta:
        model = User
        fields = [
            'id', 'username', 'email', 'nickname', 'avatar',
            'phone', 'gender', 'birthday', 'role',
            'student_id', 'major', 'grade', 'dormitory',
            'is_verified', 'is_active', 'date_joined',
            'profile'
        ]
        read_only_fields = ['id', 'date_joined', 'is_active']


class UserUpdateSerializer(serializers.ModelSerializer):
    """
    用户信息更新序列化器
    注意：不包含头像字段，头像上传应通过专门的头像上传API
    """
    
    # 添加邮箱字段并进行验证
    email = serializers.EmailField(required=True)
    
    class Meta:
        model = User
        fields = [
            'email', 'nickname', 'phone', 'gender', 'birthday',
            'student_id', 'major', 'grade', 'dormitory'
        ]
    
    def validate_phone(self, value):
        """验证手机号格式，允许空值"""
        if value and len(value) > 0 and not str(value).isdigit():
            raise serializers.ValidationError('手机号只能包含数字')
        return value


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    
    class Meta:
        model = UserAddress
        fields = [
            'id', 'receiver_name', 'receiver_phone', 
            'address', 'is_default', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']
    
    def validate_receiver_phone(self, value):
        """验证收货人手机号格式"""
        if len(value) != 11:
            raise serializers.ValidationError('手机号必须是11位数字')
        return value
    
    def create(self, validated_data):
        """创建地址时处理默认地址"""
        user = self.context['request'].user
        
        # 如果设置为默认地址，先取消其他默认地址
        if validated_data.get('is_default', False):
            UserAddress.objects.filter(user=user, is_default=True).update(is_default=False)
        
        validated_data['user'] = user
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        """更新地址时处理默认地址"""
        user = self.context['request'].user
        
        # 如果设置为默认地址，先取消其他默认地址
        if validated_data.get('is_default', False):
            UserAddress.objects.filter(user=user, is_default=True).exclude(id=instance.id).update(is_default=False)
        
        return super().update(instance, validated_data)


class UserBriefSerializer(serializers.ModelSerializer):
    """
    用户简要信息序列化器
    用于在其他模块中展示用户基本信息
    """
    
    class Meta:
        model = User
        fields = ['id', 'username', 'nickname', 'avatar', 'role']
        read_only_fields = ['id', 'username', 'role']


class PasswordChangeSerializer(serializers.Serializer):
    """
    密码修改序列化器
    """
    
    old_password = serializers.CharField(
        required=True,
        style={'input_type': 'password'}
    )
    
    new_password = serializers.CharField(
        required=True,
        validators=[validate_password],
        style={'input_type': 'password'}
    )
    
    new_password2 = serializers.CharField(
        required=True,
        style={'input_type': 'password'}
    )
    
    def validate(self, attrs):
        """验证密码"""
        if attrs['new_password'] != attrs['new_password2']:
            raise serializers.ValidationError("两次输入的新密码不一致")
        return attrs
    
    def validate_old_password(self, value):
        """验证旧密码"""
        user = self.context['request'].user
        if not user.check_password(value):
            raise serializers.ValidationError("旧密码错误")
        return value


class UserListSerializer(serializers.ModelSerializer):
    """
    用户列表序列化器（简化版）
    """
    
    class Meta:
        model = User
        fields = [
            'id', 'username', 'nickname', 'avatar', 
            'role', 'is_active', 'date_joined'
        ]
        read_only_fields = ['id', 'date_joined']
